import React, { Component } from "react";
import { Button, Col, Input, Row, Tag, Checkbox, Space, Form, InputNumber, } from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import PropTypes from "prop-types";
import TheUpload from "@/components/TheUpload";
import TheDialog from "@/components/TheDialog";
import { limitDecimals } from "@/utils/numberFixed2";
import _ from "lodash";
import '../style/style.scss'

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const skuOption = [
  { label: "文字", value: 1 },
  { label: "图片", value: 2 },
];

class Sku extends Component {
  fromRef = React.createRef();
  state = {
    skuData: {
      type: "text", //suk类型 text文字， img图片
    },
    skuType: 1,
    specifications: [],
    tableResult: [],
    dataSource: [],
    maxIndex: 0,
    numResult: [],
    checkedAllStatus: false,
    title: "",
    dialogStatus: false,
    type: "",
    resetFileList: false,
  };
  componentDidMount() {
    let skuInfo = this.props.skuInfo;
    if (this.props.skuData) {
      let { skuPropertyArray, numResult } = this.props.skuData;
      for (let i = 0; i < skuPropertyArray.length; i++) {
        skuPropertyArray[i].child.map((v) => {
          v.ischange = false;
        });
      }
      for (let j = 0; j < numResult.length; j++) {
        for (let k = 0; k < skuInfo.length; k++) {
          if (numResult[j].SKUId === skuInfo[k].SKUId) {
            skuInfo[k].fileList = numResult[j].fileList;
            skuInfo[k].skuCurrentPrice = skuInfo[k].skuCurrentPrice / 100;
            skuInfo[k].skuWeight = skuInfo[k].skuWeight / 1000;
            skuInfo[k].skuOriginalPrice = skuInfo[k].skuOriginalPrice / 100;
          }
        }
      }
      switch (skuPropertyArray.length) {
        case 1:
          this.setState({
            skuNum: null,
            skuSec: null,
            skuF: skuPropertyArray[0].child.length,
          });
          break;
        case 2:
          this.setState({
            skuNum: null,
            skuSec: skuPropertyArray[1].child.length,
            skuF: skuPropertyArray[0].child.length,
          });
          break;
        case 3:
          this.setState({
            skuNum: skuPropertyArray[2].child.length,
            skuSec: skuPropertyArray[1].child.length,
            skuF: skuPropertyArray[0].child.length,
          });
          break;
        default:
          break;
      }
      this.setState({
        specifications: skuPropertyArray,
        numResult: skuInfo,
      },
        () => {
          console.log(skuInfo, this.state.specifications, this.state.numResult, 'numResultnumResult');
          this.state.specifications.length > 0 && this.initSpecifications(this.state.specifications, true);
        }
      );

    } else {
      this.state.specifications.length > 0 && this.initSpecifications(this.state.specifications);
    }
  }

  /**
   * @desc
   * */
  skuTypeChange = (e) => {
    const skuType = e.target.value;
    this.setState({ skuType });
  };
  /**
   * @desc sku属性添加
   * */
  skuAdd = () => {
    const specifications = [...this.state.specifications];
    let status = false;
    if (specifications.length) {
      specifications.forEach((v) => {
        if (!v.name || !v.child.length) {
          status = true;
        }
      });
    }
    if (status) {
      return React.$message({
        type: "info",
        content: "请补全商品规格！",
      });
    }
    specifications.push({
      name: "", //规格名称
      child: [],
      inputVal: "",
      isHidden: false,
      isImgShow: false,
    });
    this.setState({ specifications });
  };
  /**
   * @desc 编辑suk名称
   * */
  sukEdit = (e, i) => {
    const specifications = [...this.state.specifications];
    const val = e.target.value;
    specifications[i].name = val;
    specifications[i].child.forEach((item) => {
      item.name = val;
    });
    this.setState({ specifications });
  };
  /**
   * @desc 是否显示图片信息
   * */
  skuImgChange = (e, index) => {
    const specifications = [...this.state.specifications];
    const checked = e.target.checked;
    if (checked) {
      specifications.map((v, i) => {
        v.isImgShow = i === index;
        return v;
      });
    } else {
      specifications[index].isImgShow = checked;
    }
    this.initSpecifications(specifications);
  };
  /**
   * @desc 删除sku项
   * */
  skuDelete = (i) => {
    const specifications = [...this.state.specifications];
    specifications.splice(i, 1);
    this.initSpecifications(specifications, true);
  };
  /**
   * @desc sku每子项添加
   * */
  itemAdd = (i) => {
    const specifications = [...this.state.specifications];
    let status = false;
    let skuStatus = false;
    let skuArr = specifications.map((v) => v.name);
    if (_.uniq(skuArr).length !== skuArr.length) {
      skuStatus = true;
    }
    if (skuStatus) {
      return React.$message({
        type: "info",
        content: "禁止重复添加商品规格！",
      });
    }
    let skuChildArr = specifications[i].child.map((v) => v.itemName);
    if (skuChildArr.includes(specifications[i].inputVal)) {
      status = true;
    }
    if (status) {
      React.$message({
        type: "info",
        content: "禁止重复添加SKU",
      });
      return;
    }
    if (!specifications[i].name.trim()) {
      React.$message({
        type: "info",
        content: "请输入商品规格名",
      });
      return;
    }
    if (specifications[i].inputVal.trim().length <= 0) {
      React.$message({
        type: "info",
        content: "请输入名称",
      });
      return;
    }
    specifications[i].child.push({
      name: specifications[i].name,
      itemName: specifications[i].inputVal,
      imageFile: "",
      skuOriginalPrice: "",
      // stock: "",
      skuCurrentPrice: "",
      skuWeight: "",
    });
    let numberResult = [];
    let arr = this.DescartesData(specifications);
    arr.forEach((v, i) => {
      numberResult.push({
        materialId: "",
        skuOriginalPrice: "",
        // stock: "",
        skuCurrentPrice: "",
        imageFile: "",
        isChecked: false,
        fileList: [],
        skuWeight: "",
      });
    });
    this.setState(
      {
        numResult: numberResult,
        resetFileList: true,
      },
      () => {
        this.initSpecifications(specifications, true);
        this.state.numResult.forEach((v, i) => {
          this.onUpload([], i);
        });
      }
    );
    specifications[i].inputVal = "";
  };
  /**
   * @desc sku每子项输入框修改
   * */
  itemChange = (e, i) => {
    const specifications = [...this.state.specifications];
    specifications[i].inputVal = e.target.value;
    this.setState({ specifications });
    // this.initSpecifications(specifications);
  };
  /**
   * @desc 子项删除事件
   * */
  itemDelete = (e, parentIndex, nowIndex) => {
    const specifications = [...this.state.specifications];
    const numResult = [...this.state.numResult];
    specifications[parentIndex].child.splice(nowIndex, 1);
    numResult.splice(nowIndex, 1);
    this.setState(
      {
        numResult,
      },
      () => this.initSpecifications(specifications, true)
    );
  };
  /**
   * @desc 子项编辑事件
   * */
  itemEdit = (e, parentIndex, nowIndex) => {
    const specifications = [...this.state.specifications];
    const val = specifications[parentIndex].child[nowIndex].itemName;
    specifications[parentIndex].inputVal = val;
    specifications[parentIndex].child.splice(nowIndex, 1);
    this.initSpecifications(specifications, true);
  };
  /**
   * @desc  规格设置表格数据初始化
   * */
  initSpecifications = (specifications, type, isDefault) => {
    //判断sku数据是否为空 如果为空不进行操作处理
    const tableResult = specifications.length > 0 ? this.DescartesData(specifications) : [];
    if (type) {
      this.setState({ specifications, tableResult });
    } else {
      this.setState({
        specifications,
        tableResult:
          tableResult.length === 0 ? this.state.tableResult : tableResult,
      });
    }
    // let numResult = [];
    // tableResult.forEach((v) => {
    //   numResult.push({
    //     materialId: "",
    //     SKUId: "",
    //     skuOriginalPrice: "",
    //     // stock: "",
    //     skuCurrentPrice: "",
    //     imageFile: "",
    //     isChecked: false,
    //     fileList: [],
    //   });
    // });
    // this.setState({ specifications, tableResult, numResult });
    console.log(this.state.specifications, this.state.tableResult, this.state.numResult, 'numResult');
    this.props.getSkuProperty(specifications, tableResult, this.state.skuType);
    this.props.getNumResult(this.numResultChange(specifications, isDefault),
      this.state.delete
    );
  };
  /**
   * @desc 重新渲染
   * */
  numResultChange(specifications, isDefault) {
    let res = this.DescartesData(specifications) || [];
    let numResult = JSON.parse(JSON.stringify(this.state.numResult));
    let defaultData = {
      imageFile: "",
      skuOriginalPrice: "",
      // stock: "",
      skuCurrentPrice: "",
      isChecked: false,
      fileList: [],
    };
    res = res.map((v) => {
      return defaultData;
    });
    numResult.forEach((v, i) => {
      res.forEach((m, n) => {
        if (i === n) {
          res[i] = v;
        }
      });
    });
    if (isDefault) {
      res = res.map((v) => {
        return defaultData;
      });
    }
    this.setState({ numResult: res });
    return res;
  }
  onUpload = (value, pid) => {
    const { numResult } = this.state;
    let result = JSON.parse(JSON.stringify(numResult))
    if (value.length > 0 && value[0].response && value[0].response.code === 0) {
      let obj = result[pid];
      result[pid] = {
        ...obj,
        imageFile: value[0].response.data,
        fileList: [
          {
            name: "image",
            status: "done",
            uid: 1,
            url: value[0].response.data,
          },
        ],
      };
    } else {
      result[pid].imageFile = ''
      result[pid].fileList = []
    }
    this.setState({ numResult: result, }, () => this.props.getNumResult(this.state.numResult))
  };

  /**
   * @desc 转换数据为笛卡尔数据模式
   * */
  DescartesData(arr) {
    //编辑原数组格式
    if (arr[0].child) {
      arr = arr.map((item) => {
        return (item = item.child);
      });
    }
    if (arr.length === 1) {
      //最终合并成一个
      return arr[0];
    } else {
      //有两个子数组就合并
      let arrySon = [];
      //将组合放到新数组中
      arr[0].forEach((_, index) => {
        arr[1].forEach((_, index1) => {
          arrySon.push([].concat(arr[0][index], arr[1][index1]));
        });
      });
      // 新数组并入原数组,去除合并的前两个数组
      arr[0] = arrySon;
      arr.splice(1, 1);
      // 递归
      return this.DescartesData(arr);
    }
  }

  /**
   * @desc 设置suk综合属性 原价，库存，编码数据
   * */
  inputChange = (val, i, type) => {
    const numResult = [...this.state.numResult];
    if (type === "materialId") {
      numResult[i][type] = val.trim();
    } else {
      numResult[i][type] = val;
    }
    this.props.getNumResult(numResult);
    this.setState({ numResult });
  };
  /**
   * @desc 全选事件
   * */
  allChecked = (status) => {
    let numResult = [...this.state.numResult].map((v) => {
      v.isChecked = status;
      return v;
    });

    this.setState({
      checkedAllStatus: status,
      numResult,
    });
  };
  /**
   * @desc sukCheck选中事件
   * */
  checkboxChange = (e, i, type) => {
    const val = e.target.checked;
    const numResult = [...this.state.numResult];
    numResult[i][type] = val;
    let tmp = numResult.filter((v) => v.isChecked);
    this.setState({
      numResult,
      checkedAllStatus: tmp.length === numResult.length,
    });
  };
  /**
   * @desc 批量设置数据
   * */
  bulkSetData = (type) => {
    if (this.state.numResult.filter((v) => v.isChecked).length <= 0) {
      React.$message({
        type: "info",
        content: "请选择商品sku",
      });
      return;
    }
    let title = "";
    // if (type === "stock") {
    //   title = "批量设置库存";
    // } else
    if (type === "skuCurrentPrice") {
      title = "批量设置价格";
    }
    this.setState({
      title,
      type,
      dialogStatus: true,
    });
  };
  /**
   * @desc 批量设置数据提交方法
   * */
  bulkSave = (value) => {
    if (this.state.numResult.length <= 0) {
      return;
    }
    const numResult = [...this.state.numResult].map((v) => {
      if (v.isChecked) {
        v[this.state.type] = value.bulkNum;
      }
      return v;
    });
    this.setState({ numResult, dialogStatus: false });
  };

  render() {
    const {
      skuType,
      numResult,
      checkedAllStatus,
      dialogStatus,
      title,
      type,
      resetFileList,
    } = this.state;
    let arr = this.state.specifications;
    let res = this.state.tableResult;
    let row = [];
    let rowspan = res.length;
    for (let n = 0; n < arr.length; n++) {
      row[n] = parseInt(rowspan / arr[n].child.length);
      rowspan = row[n];
    }
    console.log(numResult, 'numResult');
    const tdRow = (i) =>
      arr.map((_, j) => {
        let td;
        if (i % row[j] === 0 && row[j] > 1) {
          res[i] &&
            (td = res[i][j] && (
              <td rowSpan={row[j]} key={j}>
                <div className="tdRowName">{res[i][j].itemName}</div>
              </td>
            ));
        } else if (row[j] === 1) {
          res[i] &&
            (res[i] instanceof Array
              ? (td = res[i][j] && (
                <td key={j}>
                  <div className="tdRowName">{res[i][j].itemName}</div>
                </td>
              ))
              : (td = (
                <td key={j}>
                  <div className="rdRowName">{res[i].itemName}</div>
                </td>
              )));
        }
        return td;
      });
    return (
      <>
        <div className="spotGoods-sku-list">
          <div className="spotGoods-sku-item">
            <Row>
              <Col span={3}>
                <span className="spotGoods-item-label">商品规格：</span>
              </Col>
              <Col span={20}>
                <div className="spotGoods-Specification-box">
                  <p style={{ color: "red", marginBottom: 10 }}>
                    *修改商品规格将会清空规格设置
                  </p>
                  {arr.map((v, i) => {
                    return (
                      !v.isHidden && (
                        <div key={i} className="spotGoods-Specification-item">
                          <div className="spotGoods-Specification-model clearfix">
                            <Input
                              className={"fl"}
                              defaultValue={v.name}
                              onBlur={(e) => this.sukEdit(e, i)}
                              maxLength={100}
                            />
                            <span className={"fl"}>最多输入100个字</span>
                            {i + 1 === arr.length && (
                              <em
                                className={"fr"}
                                onClick={() => this.skuDelete(i)}
                              >
                                <DeleteOutlined />
                                删除
                              </em>
                            )}
                          </div>
                          <div className="spotGoods-model-label">
                            {v.child.map((k, n) => {
                              return (
                                <div key={n} className="spotGoods-model-tag">
                                  <Tag
                                    color="#108ee9"
                                    closable
                                    // onDoubleClick={(e) =>
                                    //   this.itemEdit(e, i, n)
                                    // }
                                    onClose={(e) => this.itemDelete(e, i, n)}
                                  >
                                    {k.itemName}
                                  </Tag>
                                </div>
                              );
                            })}
                            <div className="spotGoods-model-operation">
                              <Input
                                value={v.inputVal}
                                maxLength={100}
                                onChange={(e) => this.itemChange(e, i)}
                              />
                              <Button
                                type={"primary"}
                                size={"small"}
                                onClick={() => this.itemAdd(i)}
                              >
                                添 加
                              </Button>
                              {/* <span>双击可修改规格名称</span> */}
                            </div>
                          </div>
                        </div>
                      )
                    );
                  })}
                  {arr.length < 3 && (
                    <div
                      className="spotGoods-sku-Specification"
                      onClick={this.skuAdd}
                    >
                      <PlusOutlined style={{ fontSize: 30, color: "#999" }} />
                    </div>
                  )}
                </div>
              </Col>
            </Row>
          </div>
          {numResult.length > 0 && (
            <div className="spotGoods-sku-item">
              <Row>
                <Col span={3}>
                  <span className="spotGoods-item-label">规格设置：</span>
                </Col>
                <Col span={20}>
                  <table className="spec-table">
                    <thead>
                      <tr>
                        <th>
                          <Checkbox
                            label={"全选"}
                            onChange={(e) => this.allChecked(e.target.checked)}
                            checked={checkedAllStatus}
                          />
                        </th>
                        {arr
                          .filter((v) => v.name && v.child && v.child.length)
                          .map((th, k) => {
                            return (
                              <th key={k}>
                                <div className="property-name">{th.name}</div>
                              </th>
                            );
                          })}
                        {/* <th>物料ID</th> */}
                        <th>商品物料名称(仓库用 APP不显示)</th>

                        <th>原价</th>
                        <th>现价</th>
                        {/* <th>库存</th> */}
                        <th>重量</th>
                        <th>描述</th>
                        <th>图片</th>
                      </tr>
                      {numResult.map((v, i) => {
                        console.log(v, 'ssssss');
                        return (
                          <tr key={i}>
                            <th>
                              <Checkbox
                                onChange={(e) =>
                                  this.checkboxChange(e, i, "isChecked")
                                }
                                checked={v.isChecked}
                              />
                            </th>
                            {tdRow(i)}
                            {/* <td>
                              <Input
                                value={v.materialId}
                                maxLength={50}
                                onChange={(e) => {
                                  let val = e.target.value;
                                  this.inputChange(val, i, "materialId");
                                }}
                              />
                            </td> */}
                            <td>
                              <Input
                                value={v.materialName}
                                maxLength={100}
                                onChange={(e) => {
                                  let val = e.target.value;
                                  this.inputChange(val, i, "materialName");
                                }}
                              />
                            </td>
                            <td>
                              <InputNumber
                                min={0.01}
                                max={10000000}
                                formatter={limitDecimals}
                                value={v.skuOriginalPrice}
                                onChange={(e) =>
                                  this.inputChange(e, i, "skuOriginalPrice")
                                }
                              />
                            </td>
                            <td>
                              <InputNumber
                                min={0.01}
                                max={10000000}
                                formatter={limitDecimals}
                                value={v.skuCurrentPrice}
                                onChange={(e) =>
                                  this.inputChange(e, i, "skuCurrentPrice")
                                }
                              />
                            </td>
                            {/* <td>
                              <InputNumber
                                min={0}
                                max={10000000}
                                precision={0}
                                value={v.stock}
                                onChange={(e) =>
                                  this.inputChange(e, i, "stock")
                                }
                              />
                            </td> */}
                            <td>
                              <InputNumber
                                min={0}
                                precision={1}
                                value={v.skuWeight}
                                onChange={(e) =>
                                  this.inputChange(e, i, "skuWeight")
                                }
                              />
                            </td>
                            <td>
                              <Input
                                value={v.skuDescription}
                                onChange={(e) => {
                                  let val = e.target.value;
                                  this.inputChange(val, i, "skuDescription");
                                }}
                              />
                            </td>
                            <td>
                              <TheUpload
                                label={"上传图片"}
                                pid={i}
                                index={i}
                                len={1}
                                fileList={v.fileList}
                                getFileResult={(e) => this.onUpload(e, i)}
                              />
                            </td>
                          </tr>
                        );
                      })}
                    </thead>
                  </table>
                  <div className="spotGoods-btn-box">
                    <Space>
                      <Button
                        type="primary"
                        onClick={() => this.allChecked(true)}
                      >
                        全选
                      </Button>
                      <Button
                        type="primary"
                        onClick={() => this.allChecked(false)}
                      >
                        取消
                      </Button>
                      <Button
                        className="green-background"
                        onClick={() => this.bulkSetData("stock")}
                      >
                        批量设置库存
                      </Button>
                      <Button
                        className="green-background"
                        onClick={() => this.bulkSetData("skuCurrentPrice")}
                      >
                        批量设置价格
                      </Button>
                    </Space>
                  </div>
                </Col>
              </Row>
            </div>
          )}
        </div>
        <TheDialog
          width={600}
          visible={dialogStatus}
          title={title}
          handleCancel={() => this.setState({ dialogStatus: false })}
          footer={null}
        >
          <Form {...layout} ref={this.fromRef} onFinish={this.bulkSave}>
            <Form.Item
              label={title}
              name="bulkNum"
              rules={[{ required: true }]}
            >
              <InputNumber
                max={10000000}
                min={type === "stock" ? 0 : 0.01}
                precision={type === "stock" ? 0 : 2}
              />
            </Form.Item>
            <div className="p-text-align">
              <Space>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
                <Button onClick={() => this.setState({ dialogStatus: false })}>
                  取消
                </Button>
              </Space>
            </div>
          </Form>
        </TheDialog>
      </>
    );
  }
}

Sku.propTypes = {
  getSkuProperty: PropTypes.func,
  getNumResult: PropTypes.func,
  defaultValue: PropTypes.array,
};
Sku.defaultProps = {
  defaultValue: [],
};
export default Sku;
